package com.athuahua.spzx.service.impl;

import com.athuahua.spzx.entity.SysUserRole;
import com.athuahua.spzx.mapper.SysUserRoleMapper;
import com.athuahua.spzx.dto.system.SysRoleDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.SysRole;
import com.athuahua.spzx.service.SysRoleService;
import com.athuahua.spzx.mapper.SysRoleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author huahua
* @description 针对表【sys_role(角色)】的数据库操作Service实现
* @createDate 2024-07-22 23:01:08
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService{
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public IPage<SysRole> findByPage(int page, int size, SysRoleDto sysRoleDto) {
        IPage<SysRole> iPage = new Page<>(
                page,
                size
        );

        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询
        queryWrapper.like(sysRoleDto.getRoleName() != null, SysRole::getRoleName, sysRoleDto.getRoleName())
                .orderByDesc(SysRole::getUpdateTime);

        return sysRoleMapper.selectPage(iPage, queryWrapper);
    }

    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        Map<String, Object> result = new HashMap<>();
        //查询所有角色
        List<SysRole> sysRoles = sysRoleMapper.selectList(null);


        //查询当前用户已被分配的角色列表
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);



        //将角色列表转换为id列表返回给前端
        List<Long> sysUserRoleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).toList();



        result.put("allRolesList",sysRoles);
        result.put("sysUserRoles",sysUserRoleIds);
        return result;
    }
}




